package chat.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;


public class ChatClientActivity extends Activity {
	
	private static String IP = "192.168.0.196";
	
	ScrollView scrollView;
	TextView textView;
    EditText editText;
    Button sendButton;
	private Handler mHandler = new Handler();
	String input = null;
	
	ChatClient cc;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				input = editText.getText().toString();
				editText.setText("");
				if(textView.getText().equals("")){
					textView.append(input);
				}
				textView.append("\n" + input);
				scrollView.fullScroll(View.FOCUS_DOWN);
			}
		});
        textView.setMovementMethod(new ScrollingMovementMethod());
        Save save = (Save)getApplication();
        Socket s = save.getSocket();
		String name = save.getUserName();
		//cc = new ChatClient(name, s);
    }
    
    private void scrollDown() {
        scrollView.smoothScrollTo(0, scrollView.getBottom());
}

    
    private void setText(final String text, final boolean newline){
    	mHandler.post(new Runnable() {
			
			public void run() {
				textView.append(text);
				if(newline){
					textView.append("\n");
				}
				textView.scrollTo(0, textView.getHeight());
			}
		});
    }
   
    public class ChatClient {
    	boolean connected = false;
    	Socket connection;
    	ExecutorService executor;
    	String userName;
    	String chatName = "You";

    	//BufferedReader consoleReader = new BufferedReader(new InputStreamReader());
    	PrintWriter socketWriter = null;
    	BufferedReader socketReader = null;
    	InetAddress serverip;
    	
    	public ChatClient(String name, Socket s){
    		userName = name;
    		executor = Executors.newFixedThreadPool(2);
    		this.serverip = s.getInetAddress();
//    		try {
//    			int port = Integer.parseInt(new BufferedReader(new InputStreamReader(s.getInputStream())).readLine());
//    			s.setReuseAddress(true);
//    			s.close();
//    			s=null;
//    			ServerSocket serv = new ServerSocket(port);
//    			Socket sock = serv.accept();
//    			setSocket(sock);
//    			socketWriter.println(userName);
//    		} catch (IOException e) {
//    			// TODO Auto-generated catch block
//    			System.err.println("Failed to connect to server");
//    			e.printStackTrace();
//    			System.exit(-1);
//    		}
			setSocket(s);
    		new Thread(new SocketListener()).start();
    		new Thread(new ConsoleListener()).start();
    	}

    	private class SocketListener implements Runnable {

    		public SocketListener(){
    		}

    		public void run() {
    			try {
    				//Socket socket
    				while(true){
    					if(!connected){
    						while(!socketReader.ready()){ 
    							if(connected){
    								break;
    							}
    						}
    						if(connected){
								continue;
							}
    						String in = socketReader.readLine();
    						if(in!=null){
    							//System.out.println(in);
    							setText(in,true);
    						} else {
    							setText("Connection aborted",true);
    							System.exit(0);
    						}
    						String chatstart = "Chat started with ";
    						if(in.startsWith(chatstart)){
    							connected = true;
    							chatName = in.substring(chatstart.length());
    						}
    						if(in.equals("Username not available")){
    							connection.close();
    							System.exit(0);
    						}
    					} else{
    						while(!socketReader.ready()){
    							if(!connected){
    								return;
    							}
    						}
    						String in = socketReader.readLine();
    						if(in==null){
    							setText("Connection aborted",true);
    							connection.close();
    							System.exit(0);
    						}
    						setText(chatName+": "+in,true);
    					}
    				}
    			} catch (SocketException e) {
    				// TODO Auto-generated catch block
    				//e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		
    	}

    	private class ConsoleListener implements Runnable {

    		public ConsoleListener(){
    		}

    		public void run() {
    			while(true){
    				try{
    					String line;
    					if(connected){
    						line = getLine();
    						setText(userName + ": " + editText.getText().toString(),true);
    					} else {
    						line = readLineStopWhenConnected();
    						if(line==null){
    							continue;
    						}
    					}
    					if(line.equalsIgnoreCase("exit")){
    						socketWriter.println("exit");
    						connection.close();
    						return;
    					}
    					socketWriter.println(line);
    				}catch (UnknownHostException eh) {
    					// TODO: handle exception
    					System.err.println("bad IP");
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					System.err.println("Failed to read");
    				}

    			}
    		}
    		
    		private String getLine() {
				while(input==null){	}
				String temp = input;
				input = null;
				return temp;
			}

			private String readLineStopWhenConnected() throws IOException {
				while(input==null){
					if(connected){
						return null;
					}
				}
				String temp = input;
				input = null;
				return temp;
    		}

    	}

    	/*
    	 * 
    	 * @param socket
    	 */
    	public void setSocket(Socket socket) {
    		//Skapa ny socket connection med ip från socket och port från socket.in
    		//skicka ip som ska kontaktas.

    		connection = socket;
    		try {
    			socketWriter = new PrintWriter(connection.getOutputStream(),true);
    			socketReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}

    }
    
    
    
}